package com.maddox.relax.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.maddox.relax.R;
import com.maddox.relax.util.AppUtils;

import java.io.File;
import java.io.IOException;

/**
 * 重写播放器
 * 可以自动生成缩略图以及时长
 */
public class MVideoView extends LinearLayout {

    private VideoView videoView;
    private ImageView bgimage, btnPlay;
    private TextView durationTv;
    private String videoUri;


    public MVideoView(Context context) {
        this(context, null);
    }

    public MVideoView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutInflater.from(context).inflate(R.layout.layout_video_play, this);
        videoView = findViewById(R.id.videoview);
        btnPlay = findViewById(R.id.btnplay);
        bgimage = findViewById(R.id.bgimage);
        durationTv = findViewById(R.id.tv_duration);
        btnPlay.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(videoUri)) {
                btnPlay.setVisibility(INVISIBLE);
                bgimage.setVisibility(INVISIBLE);
                videoView.setVideoURI(Uri.fromFile(new File(videoUri)));
                videoView.start();
            }
        });
        videoView.setOnCompletionListener(mp -> {
            bgimage.setVisibility(VISIBLE);
            btnPlay.setVisibility(VISIBLE);
        });
    }

    public void setVideoUri(String videoUri) {
        this.videoUri = videoUri;
        //创建线程获取视频相关信息
        new Thread(() -> {
            //获取视频第一帧截图
            Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoUri, MediaStore.Video.Thumbnails.MINI_KIND);
            if (bitmap != null) {
                //转换成指定大小的图
                // bitmap = ThumbnailUtils.extractThumbnail(bitmap,width,height,ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
                bgimage.post(() -> {
                    bgimage.setImageBitmap(bitmap);
                });
            }
            //获取视频时长
            MediaPlayer mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(videoUri);
                mediaPlayer.prepare();
                int duration = mediaPlayer.getDuration();
                durationTv.post(()->{
                    durationTv.setText(AppUtils.getVideoDuration(duration));
                });
            } catch (IOException e) {
                e.printStackTrace();
            }

        }).start();
    }
}
